const express = require('express');
const path = require('path');
const fs = require('fs');

// 导入业务模块
const AIService = require('./main/ai-service');
const DocumentExporter = require('./main/document-exporter');
// 暂时注释掉数据库相关功能，因为我们移除了sqlite3
// const DatabaseManager = require('./main/database-manager');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(express.json());
app.use(express.static(path.join(__dirname, 'renderer')));

// 初始化服务
let aiService;
let documentExporter;
// let dbManager;

try {
  aiService = new AIService();
  documentExporter = new DocumentExporter();
  // dbManager = new DatabaseManager();
  // dbManager.initialize();
} catch (error) {
  console.error('服务初始化失败:', error);
}

// 路由
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'renderer', 'index.html'));
});

// API 路由
app.post('/api/generate-topics', async (req, res) => {
  try {
    const { preferences } = req.body;
    const result = await aiService.generateTopics(preferences);
    res.json({ success: true, data: result });
  } catch (error) {
    console.error('生成主题失败:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

app.post('/api/generate-article', async (req, res) => {
  try {
    const { topic, options } = req.body;
    const result = await aiService.generateArticle(topic, options);
    res.json({ success: true, data: result });
  } catch (error) {
    console.error('生成文章失败:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

app.post('/api/export-to-word', async (req, res) => {
  try {
    const { content, filename } = req.body;
    const filePath = path.join(__dirname, '..', 'exports', filename || '技术文章.docx');
    
    // 确保导出目录存在
    const exportDir = path.dirname(filePath);
    if (!fs.existsSync(exportDir)) {
      fs.mkdirSync(exportDir, { recursive: true });
    }
    
    await documentExporter.exportToWord(content, filePath);
    res.json({ success: true, filePath: filePath });
  } catch (error) {
    console.error('导出Word失败:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

// 暂时使用内存存储替代数据库
let articles = [];
let settings = {};
let topics = [];

app.post('/api/save-article', async (req, res) => {
  try {
    const article = req.body;
    article.id = Date.now().toString();
    article.created_at = new Date().toISOString();
    articles.push(article);
    res.json({ success: true, data: article });
  } catch (error) {
    console.error('保存文章失败:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

app.get('/api/article-history', async (req, res) => {
  try {
    const limit = parseInt(req.query.limit) || 50;
    const result = articles.slice(-limit).reverse();
    res.json({ success: true, data: result });
  } catch (error) {
    console.error('获取历史记录失败:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

app.get('/api/settings', async (req, res) => {
  try {
    res.json({ success: true, data: settings });
  } catch (error) {
    console.error('获取设置失败:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

app.post('/api/save-settings', async (req, res) => {
  try {
    const newSettings = req.body;
    settings = { ...settings, ...newSettings };
    
    // 更新AI服务配置
    if (settings.ai_provider && settings.api_key) {
      aiService.setApiConfig(settings.ai_provider, settings.api_key, settings.api_base_url);
    }
    
    res.json({ success: true, data: settings });
  } catch (error) {
    console.error('保存设置失败:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

app.get('/api/topics', async (req, res) => {
  try {
    const limit = parseInt(req.query.limit) || 20;
    const result = topics.slice(-limit).reverse();
    res.json({ success: true, data: result });
  } catch (error) {
    console.error('获取主题失败:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

app.post('/api/save-topic', async (req, res) => {
  try {
    const topic = req.body;
    topic.id = Date.now().toString();
    topic.created_at = new Date().toISOString();
    topics.push(topic);
    res.json({ success: true, data: topic });
  } catch (error) {
    console.error('保存主题失败:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

app.get('/api/article/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const article = articles.find(a => a.id === id);
    if (article) {
      res.json({ success: true, data: article });
    } else {
      res.status(404).json({ success: false, error: '文章未找到' });
    }
  } catch (error) {
    console.error('获取文章失败:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

app.delete('/api/article/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const index = articles.findIndex(a => a.id === id);
    if (index !== -1) {
      articles.splice(index, 1);
      res.json({ success: true });
    } else {
      res.status(404).json({ success: false, error: '文章未找到' });
    }
  } catch (error) {
    console.error('删除文章失败:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`AI2Word 服务器运行在 http://localhost:${PORT}`);
  console.log('开发模式: 在浏览器中打开上述地址');
});

module.exports = app;